<?php

namespace app\admin\controller\store;

use app\admin\model\halt\Cate;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 分类管理
 *
 * @icon fa fa-circle-o
 */
class Haltcate extends Backend
{
    
    /**
     * Cate模型对象
     * @var \app\admin\model\halt\Cate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        parent::_initialize();
        $this->request->filter(['strip_tags']);

        $this->model = model('app\admin\model\halt\Cate');
        $type = $this->request->request("type");

        $tree = Tree::instance();
        if ($type==2 ){
            $where['id']=array("gt",215);
            $tree->init(collection($this->model->where($where)->order('id asc')->select())->toArray(), 'pid');
        }else{
            $tree->init(collection($this->model->order('id asc')->select())->toArray(), 'pid');
        }

        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $categorydata = [0 => ['type' => '1', 'name' => __('None')]];

        if ($type==null)$type=1;
        foreach ($this->categorylist as $k => $v)
        {
            if ($v['type']==$type) {
                $categorydata[$v['id']] = $v;
            }
        }

        $this->assignconfig('type',$type);
        $this->assign('type',$type);
        $this->view->assign("parentList", $categorydata);
        $this->view->assign("typeList", $this->model::getTypeList());


        /* echo '<pre>';
         var_dump($categorydata);*/

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            build_radios('row[status]', ['normal'=>__('Normal'), 'hidden'=>__('Hidden')]);
            $search = $this->request->request("search");
            $type = $this->request->get("type");

            if ($type==null)$type=1;

            //构造父类select列表选项数据
            $list = [];
            foreach ($this->categorylist as $k => $v)
            {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false)
                    {
                        if($type == "all" || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if($type == "all" || $type == null) {
                        $list = $this->categorylist;
                    } else if ($v['type'] == $type){
                        $list[] = $v;
                    }

                }

            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function import()
    {
        header("Content-type:text/html;charset=utf-8");
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;

        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        ob_end_clean();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $PHPReader = new \PHPExcel_Reader_CSV();
                if (!$PHPReader->canRead($filePath)) {
                    $this->error(__('Unknown data format'));
                }
            }
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $PHPExcel = $PHPReader->load($filePath); //加载文件
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);

        $db = new Cate();

        for ($currentRow = 1078; $currentRow <= 1082; $currentRow++) {
            $val = $currentSheet->getCellByColumnAndRow(3, $currentRow)->getValue();
            if ($val!=null){
                $db->insert(array('name'=>str_replace(" ",'',$val),'createtime'=>time(),'updatetime'=>time(),'pid'=>121));

            }
        }




        $this->success();
    }
    public function add()
    {
        $pid = $this->request->request("ids");
        $type = $this->request->request("type");

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    $list = explode("|",$params["name"]);

                    foreach ($list as $v){
                        $this->model->insert(
                            array(
                                "type"=>$params['type'],
                                "pid"=>$params['pid'],
                                "name"=>$v,
                                "createtime"=>time(),
                                "updatetime"=>time()

                            )
                        );
                    }


                    $this->error('添加成功');
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("pid", $pid);
        return $this->view->fetch();
    }

    //编辑
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        reduce_stock(2,array(array("id"=>4,"num"=>1)),"admin");

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
